import React, { FC, useEffect, useState, createElement } from 'react';
import { Button, Upload, UploadFile, UploadProps } from 'antd';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import { CardContent } from './card-content';
import './baseFieldUpload.module.less';
import { API_URL } from '../../../../../lowcode/_setters/config';
import { Request } from '../../../utils/request';

export async function uploadAppFile(uploadAppFileDto: any) {
  return Request.upload(API_URL + '/app/file/upload', uploadAppFileDto);
}
export const BaseFieldUpload: FC<any> = (props) => {
  const { style, className, columnConfig, uploadProps, value, onChange, type } = props;

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const isFile = type === 'file';

  useEffect(() => {
    // 转换
    if (Array.isArray(value)) {
      const newValue = (value as any)?.map((item) => {
        return {
          // uid: item.id,
          // name: item.name,
          // status: 'done',
          // response: { data: [item] },
          // url: item.rul,
          ...item,
        };
      });
      setFileList((newValue as unknown) as UploadFile[]);
    }
  }, [value]);

  const uploadContent = () => {
    if (columnConfig?.uploadType === 1) {
      return (
        <Button disabled={uploadProps?.disabled} icon={<UploadOutlined />}>
          {columnConfig?.uploadText}
        </Button>
      );
    }
    if (columnConfig?.uploadType === 3) {
      return <CardContent columnConfig={columnConfig} fileList={fileList} />;
    }
  };

  const customRequest: UploadProps['customRequest'] = async (props) => {
    const { onError, onSuccess, file, data, filename } = props;
    // console.log('q=>customRequest', file);
    try {
      const res = await uploadAppFile({
        file,
      });
      onSuccess?.(res);
    } catch (e: any) {
      onError?.(e);
    }
  };

  const currUploadProps = {
    // customRequest,
    action: '/api/v1/upload',
    headers: {
      token: localStorage.getItem('user_token'),
    },
    // headers: getRequestHeader(),
    multiple: columnConfig?.selectType === 'multiple',
    maxCount: columnConfig?.maxCount,
    disabled: uploadProps.disabled,
    fileList,
    onChange: ({ file, fileList }) => {
      // 把成功的内容报错服务端
      setFileList(fileList);
      if (file.status !== 'uploading') {
        onChange?.(fileList);
      }
    },
  };

  if (columnConfig?.uploadType === 2) {
    return (
      <Upload.Dragger className={className} {...uploadProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或者拖动文件到虚线框内</p>
        <p className="ant-upload-hint">{isFile ? '支持所有类型的文件' : '支持image/*类型的文件'}</p>
      </Upload.Dragger>
    );
  }
  return (
    <Upload
      style={style}
      {...currUploadProps}
      listType={columnConfig?.uploadType === 3 ? 'picture-card' : 'text'}
    >
      {uploadContent()}
    </Upload>
  );
};
